package action.newelifile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

import org.xmlpull.v1.XmlPullParser;

import action.util.LoadSetting;
import action.util.Tool;
import action.util.UsersDAO;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SettingActivity extends Activity {

	Spinner displaySpinner,languageSpinner,chooseIconSpinner,backgroundSpinner;	
	ProgressDialog mProgressDialog;
	UsersDAO usersDAO;
	PackageInfo info;
	public static String URL_LIST_PRODUCT = "http://14.63.212.204/eli-android-center/data/auto-update/listitem.xml";
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	String link = "";
	String newversion="";
	String oldversion="";

	protected void onCreate(Bundle savedInstanceState) {
		try{
			LoadSetting.load(this);
			super.onCreate(savedInstanceState);
			initLocale();
			setContentView(R.layout.setting);

			usersDAO = new UsersDAO(this);

			displaySpinner = (Spinner) findViewById(R.id.snDisplay);
			languageSpinner = (Spinner) findViewById(R.id.snLanguage);
			backgroundSpinner = (Spinner) findViewById(R.id.snBackground);
			chooseIconSpinner = (Spinner) findViewById(R.id.snChooseIcon);


			displaySpinner.setSelection(LoadSetting.setting.getDisplay());
			languageSpinner.setSelection(LoadSetting.setting.getLanguage());
			backgroundSpinner.setSelection(LoadSetting.setting.getBackground());
			chooseIconSpinner.setSelection(LoadSetting.setting.getIcon());
			((TextView)findViewById(R.id.title_setting)).setText(getString(R.string.menu_option_titleSetting));
			((TextView)findViewById(R.id.tvVersionName)).setText(info.versionName);
			((Button)findViewById(R.id.updateButton)).setOnClickListener(checkForUpdate());
		}catch(Exception e){
			e.printStackTrace();
			Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}

	}

	public void initLocale(){
		try {
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		String languageToLoad = Tool.locale(LoadSetting.setting.getLanguage());  
		Locale locale = new Locale(languageToLoad);   
		Locale.setDefault(locale);  
		Configuration config = new Configuration();  
		config.locale = locale;  
		getBaseContext().getResources().updateConfiguration(config,   
				getBaseContext().getResources().getDisplayMetrics());  
	}



	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			loading();
		}
		return super.onKeyDown(keyCode, event);
	}

	private void loading() {
		new AsyncTask<String, String, Void>() {


			protected void onPreExecute() {
				mProgressDialog = ProgressDialog.show(SettingActivity.this, "",
						getString(R.string.saving) + "...", true);
			}

			protected void onProgressUpdate(String... progress) {
				mProgressDialog.setMessage(progress[0]);
			}


			protected Void doInBackground(String... arg0) {
				publishProgress(getString(R.string.saving)+"...");
				usersDAO.saveData(backgroundSpinner.getSelectedItemPosition(),displaySpinner.getSelectedItemPosition(),languageSpinner.getSelectedItemPosition(),chooseIconSpinner.getSelectedItemPosition());
				Intent intent = getIntent();
				switch (Tool.position) {
				case 1:
					intent = new Intent(SettingActivity.this,LocalActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
					break;
				case 2:
					intent = new Intent(SettingActivity.this,LanActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();			
					break;
				case 3:
					intent = new Intent(SettingActivity.this,FtpActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
					break;
				default:
					break;
				}
				return null;
			}


			protected void onPostExecute(Void arg) {
				if (mProgressDialog.isShowing()) {
					mProgressDialog.dismiss();
				}
			}
		}.execute("");
	}



	private OnClickListener checkForUpdate(){
		OnClickListener action = new OnClickListener() {
			public void onClick(View v) {
				checkUpdate();
			}
		};
		return action;
	}

	private void checkUpdate(){
		if(getCheckProduct()==false){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.update_new_version));
			builder.setMessage(getString(R.string.ELiFile_find_new_version)+newversion+"\n"
					+ getString(R.string.would_you_like_to_update));
			builder.setPositiveButton(getString(R.string.ok),
					new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,int which) {
							downloading();
						}
					});
			builder.setNegativeButton(getString(R.string.cancel),
					new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int which) {
						}
					});
			builder.show();
		}else{
			Toast.makeText(this, getString(R.string.your_application_has_newest_version), Toast.LENGTH_SHORT).show();
		}
	}
	


	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage(getString(R.string.downloading)+" ...");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}


	public void downloading() {
		new AsyncTask<String, String, String>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showDialog(DIALOG_DOWNLOAD_PROGRESS);
			}

			protected void onProgressUpdate(String... progress) {
				mProgressDialog.setProgress(Integer.parseInt(progress[0]));
			}

			@Override
			protected void onPostExecute(String unused) {
				dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
				finish();
			}

			@Override
			protected String doInBackground(String... arg0) {
				try {
					URL url = new URL(link);
					HttpURLConnection c = (HttpURLConnection) url
							.openConnection();
					c.setRequestMethod("GET");
					c.setDoOutput(true);
					c.connect();

					File file = new File(
							Environment.getExternalStorageDirectory()
									+ "/elicenter/");
					if (!file.exists()) {
						file.mkdir();
					}

					file = new File(Environment.getExternalStorageDirectory()
							+ "/elicenter/" + "EliFile.apk");
					if (!file.exists()) {
						file.createNewFile();
					}

					File outputFile = new File(
							Environment.getExternalStorageDirectory()
									+ "/elicenter/" + "EliFile.apk");
					FileOutputStream fos = new FileOutputStream(outputFile);

					InputStream is = c.getInputStream();

					byte[] buffer = new byte[1024];

					long total = 0;
					int count;
					int lenghtOfFile = c.getContentLength();
					while ((count = is.read(buffer)) != -1) {
						total += count;
						publishProgress(""
								+ (int) ((total * 100) / lenghtOfFile));
						fos.write(buffer, 0, count);
					}

					fos.flush();
					fos.close();
					is.close();

					Intent intentInstall = new Intent(Intent.ACTION_VIEW);
					intentInstall.setDataAndType(Uri.fromFile(new File(
							Environment.getExternalStorageDirectory()
									+ "/elicenter/" + "EliFile.apk")),
							"application/vnd.android.package-archive");
					startActivity(intentInstall);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		}.execute("");
	}
	
	
	public boolean getCheckProduct() {
		try {
			PackageInfo manager = getPackageManager().getPackageInfo(getPackageName(), 0);
			XmlPullParser xmlPullParser = Xml.newPullParser();

			URL url = new URL(URL_LIST_PRODUCT);
			xmlPullParser.setInput(url.openStream(), "UTF-8");

			int eventType;
			@SuppressWarnings("unused")
			String name, size, icon, version, link1, description, pkg;
			int versionCode = 0;
			name = size = icon = version = link1 = description = pkg = "";
			while ((eventType = xmlPullParser.next()) != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					if (xmlPullParser.getName().equals("name")) {
						name = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("package")) {
						pkg = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("size")) {
						size = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("version")) {
						version = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("version-code")) {
						versionCode = Integer.parseInt(xmlPullParser.nextText());
					} else if (xmlPullParser.getName().equals("link")) {
						link1 = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("description")) {
						description = xmlPullParser.nextText();
						if(pkg.equals(manager.packageName)){
							if(versionCode>manager.versionCode){
								oldversion=manager.versionName;
								newversion=version;
								link=link1;
								return false;
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
		return true;
	}
}
